package com.yc.jpyy.mobile.service.imp;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.common.Common;
import com.yc.jpyy.mobile.dao.BizDao;
import com.yc.jpyy.mobile.dao.TeacherDao;
import com.yc.jpyy.mobile.service.CommonService;
import com.yc.jpyy.mobile.service.TeacherService;

@Service
public class TeachServiceImpl extends CommonService implements TeacherService {
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private BizDao bizDao;

	@Override
	public RestResponse teacherLogin(Map<String, Object> paramsMap,
			RestResponse response) throws DataAccessException {
		List<Map<String, Object>> stumap = teacherDao.teacherLogin(paramsMap);
		if (null != stumap && stumap.size() > 0) {
			if (stumap.get(0).get("UploadStatus").hashCode() == 2
					|| stumap.get(0).get("UploadStatus").hashCode() == 3) {
				response.setData(stumap);
			} else {
				response.setErrorcode(1);
				response.setMessage("信息未备案！");
			}
		} else {
			response.setErrorcode(1);
			response.setMessage("身份证号或密码错误");
		}
		return response;
	}

	// 修改教练电话
	@Override
	public int updateTeacherPhoneById(Map<String, Object> paramsMap)
			throws DataAccessException {

		return teacherDao.updateTeacherPhoneById(paramsMap);
	}

	@Override
	public RestResponse updateTeacherPassword(String teacherId, String newsPwd,
			String oldPwd, RestResponse response) throws DataAccessException,
			Exception {
		List<Map<String, Object>> result = teacherDao
				.getTeacherOldPwdByID(teacherId);
		if (null != result && result.size() > 0) {
			// 系统中旧密码
			String oldPwds = result.get(0).get("password").toString();
			if (oldPwds.equals(Common.genMDInfo(oldPwd))) {
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				// 修改
				paramsMap.put("id", teacherId);
				paramsMap.put("newPwd", Common.genMDInfo(newsPwd));
				int count = teacherDao.updateTeacherPwd(paramsMap);
				if (count <= 0) {
					response.setErrorcode(1);
					response.setMessage("密码修改失败");
				}
			} else {
				response.setErrorcode(1);
				response.setMessage("旧密码错误");
			}
		} else {
			response.setErrorcode(1);
			response.setMessage("无此用户");
		}
		return response;
	}

	@Override
	public RestResponse forgetTeachpassword(String mobilePhone,
			String IdCardNo, RestResponse response) throws DataAccessException {
		List<Map<String, Object>> result = teacherDao.getTeacherData(
				mobilePhone, IdCardNo);
		if (null != result && result.size() > 0) {
			response.setErrorcode(0);
			response.setData(result.get(0));
		} else {
			response.setErrorcode(1);
			response.setMessage("无此用户");
		}
		return response;
	}

	@Override
	public RestResponse updateNewPassword(Map<String, Object> paramsMap,
			RestResponse response) throws DataAccessException {
		int count = teacherDao.updateTeacherPwd(paramsMap);
		if (count <= 0) {
			response.setErrorcode(1);
			response.setMessage("密码修改失败");
		}
		return response;
	}
	// 获取系统公告信息
	@Override
	public RestResponse getNews(Map<String, Object> paramsMap,
			RestResponse response) throws DataAccessException {
		checkParamsMapForPage(paramsMap);
		List<Map<String, Object>> listData = teacherDao.getNews(paramsMap);
		if (null != listData && listData.size() > 0) {
			// 设置数据集合
			response.setData(listData);
		} else {
			response.setErrorcode(1);
			response.setMessage("无驾校通知信息！");
		}
		return response;
	}

	// 根据课程ID获取预约信息
	@Override
	public List<Map<String, Object>> getAppointmentDetailByCourseID(
			String courseID, String imgUrl) throws DataAccessException {

		return teacherDao.getAppointmentDetailByCourseID(courseID, imgUrl);
	}

	// 缺勤标记
	@Override
	public RestResponse updateAppointmentDetailAbsent(String appointId,String studentId,RestResponse response)
			throws DataAccessException {
		String courseStartTime = teacherDao.getCourseStartTime(appointId);
		DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime time = LocalDateTime.parse(courseStartTime.substring(0, courseStartTime.indexOf(".")), fmt);
		LocalDateTime now = LocalDateTime.now();
		if(courseStartTime != null && !courseStartTime.equals("") && now.isAfter(time)){
			//标记缺勤
			int i = teacherDao.updateAppointmentDetailAbsent(appointId);
			if(i > 0){
				//查询该学员是否标记三次，达到三次，拉入黑名单
				int j = teacherDao.checkStudentAbsentCount(studentId);
				if(j >=3 ){
					//查询是否有黑名单记录(如果有，则直接更改记录为拉黑状态，并增加拉黑次数，如果没有，则添加记录)
					int blackRecord = teacherDao.selectStudentBlack(studentId);
					if(blackRecord > 0){
						int updateCount = teacherDao.updateStudentBlack(studentId);
						if(updateCount <= 0){
							response.setErrorcode(1);
							response.setMessage("拉入黑名单失败...");
						}
					}else{
						int k = teacherDao.addStudentBlack(studentId);
						if(k <= 0){
							response.setErrorcode(1);
							response.setMessage("拉入黑名单失败...");
						}
					}
				}
			}else{
				response.setErrorcode(1);
				response.setMessage("标记缺勤失败...");
			}
		}else{
			response.setErrorcode(1);
			response.setMessage("课程未开始，不能标记缺勤...");
		}
		return response;
	}

	@Override
	public List<Map<String, Object>> getCourseCountByTecID(String teacherid)
			throws DataAccessException {
		return teacherDao.getCourseCountByTecID(teacherid);
	}

	@Override
	public RestResponse getCourseListByTecID(Map<String, Object> paramsMap,
			RestResponse response) throws DataAccessException {
		List<Map<String, Object>> stumap = teacherDao.getCourseListByTecID(paramsMap);
		if (stumap != null && stumap.size() > 0) {
			stumap.stream().forEach(map -> {
				map.put("studentInfo",getAppointmentDetailByCourseID(map.get("courseId").toString(), Config.getImageAddress()));
			});
			response.setData(stumap);
		} else {
			response.setErrorcode(1);
			response.setMessage("该教练下无课程信息...");
		}
		return response;
	}

	// 教课学员查询接口(学习进度列表页)
	@Override
	public List<Map<String, Object>> getTeacherStuListByTecID(String teacherid)
			throws DataAccessException {

		return teacherDao.getTeacherStuListByTecID(teacherid);
	}

	// 历史课程查询接口 根据教练ID、年月（2017-03）
	@Override
	public List<Map<String, Object>> getOldTeacherList(
			Map<String, Object> paramsMap) throws DataAccessException {

		return teacherDao.getOldTeacherList(paramsMap);
	}

	@Override
	public List<Map<String, Object>> getTeacherInfo(
			Map<String, Object> paramsMap) throws DataAccessException {
		return teacherDao.getTeacherInfo(paramsMap);
	}

	@Override
	public List<Map<String, Object>> getTechStudents(String Coachnum,
			String imgUrl) throws DataAccessException {
		return teacherDao.getTechStudents(Coachnum, imgUrl);
	}

	@Override
	public List<Map<String, Object>> getCoachSignResultForTerminater(
			String Coachnum) throws DataAccessException {
		return teacherDao.getCoachSignResultForTerminater(Coachnum);
	}

	@Override
	public Map<String, Object> getTeacherInfoForFaceCheck(
			Map<String, Object> paramsMap) throws DataAccessException {
		return teacherDao.getTeacherInfoForFaceCheck(paramsMap);
	}

	public RestResponse signinConfirm(String UID,String Type,String ObjectNum,
			String EventType,String Devnum,Map<String, Object> map,RestResponse response)
					throws Exception {
		/*String remindString ="身份证标识已存在，请联系客服！";
		if(null != UID && !UID.isEmpty()){
			//type=1教练；type=2学员
			if(Integer.parseInt(Type) == 1){
				//根据ObjectNum获取教练的UId
				String coachUID = teacherDao.getUIDForFaceCheck(ObjectNum);
				//如果教练的UId存在且不为空(第一次登陆才传身份证号，这时库里教练的身份证是不存在的，如果存在则提示身份标识已存在)
				if(null != coachUID && !coachUID.equals("")){
					 response.setErrorcode(1);
					 response.setMessage(remindString);
				}else{
					 //查询该UID是否存在（除了ObjectNum对应的记录，其他记录里是否存在该UID）
				     int uIdCount = teacherDao.isExistUIDForFaceCheck(UID);
				     //如果存在则提示身份标识已存在
					 if(uIdCount > 0){
						 response.setErrorcode(1);
						 response.setMessage(remindString);
					 }else{
						 //第一次登陆，如果库里不存在，则把身份证号更新进去（以后登录不会再传身份证号）
						 teacherDao.updateUIDForFaceCheck(UID, ObjectNum); 
						 //验证设备编号(VehicleId和gpsId)并访问二维码比对接口
						 LoginAndOutController.checkDevNum(response,Devnum,ObjectNum,Type,EventType,map);
					 }
				}
			}else if(Integer.parseInt(Type)==2){
				//学员同教练原理一样
				String stuUID = bizDao.getUIDForFaceCheck(ObjectNum);
				if(null != stuUID && !stuUID.equals("")){
					 response.setErrorcode(1);
					 response.setMessage(remindString);
				}else{
				     int uIdCount = bizDao.isExistUIDForFaceCheck(UID);
					 if(uIdCount > 0){
						 response.setErrorcode(1);
						 response.setMessage(remindString);
					 }else{
						 bizDao.updateUIDForFaceCheck(UID, ObjectNum);
						 //验证设备编号并访问二维码比对接口
						 LoginAndOutController.checkDevNum(response,Devnum,ObjectNum,Type,EventType,map);
					 }
				}
			}
		}else{
			//不是第一次登录（扫码），则直接验证设备编号并访问二维码比对接口
			LoginAndOutController.checkDevNum(response,Devnum,ObjectNum,Type,EventType,map);
		}*/
		return response;
   }

	
	@Override
	public List<Map<String, Object>> getAppointMentTeachCourses(String coachNum)
			throws DataAccessException {
		return teacherDao.getAppointMentTeachCourses(coachNum);
	}

	@Override
	public List<Map<String, Object>> getTrainingRecords(
			Map<String, Object> paramsMap) throws DataAccessException {
		return teacherDao.getTrainingRecords(paramsMap);
	}

	@Override
	public RestResponse addTeacherLeave(Map<String, Object> paramsMap,
			RestResponse response) throws DataAccessException {
		//获取请假时间段内该教练所对应的课程ID
		List<Map<String,Object>> courseIdMap = teacherDao.getCourseIds(paramsMap);
		List<String> courseId = new ArrayList<>();
		for(int i = 0;i < courseIdMap.size();i ++){
			courseId.add(courseIdMap.get(i).get("id").toString());
		}
		//list转string
		String courseIds = "";
		if(courseId != null && courseId.size() > 0){
			boolean flag = false;
			for (String string : courseId) {
				if (flag) {
					courseIds = courseIds + ",";
				} else {
					flag = true;
				}
				courseIds = courseIds + string;
			}
			paramsMap.put("courseIds", courseIds);
		}else{
			paramsMap.put("courseIds", "");
		}
		//paramsMap.put("courseIds", "40308,40311,40312,40579,40580,40581,40583,40585,40586");
		//添加教练请假信息
		int i = teacherDao.addTeacherLeave(paramsMap);
		if (i > 0) {
			response.setErrorcode(0);
			response.setMessage("请假已提交...");
		} else {
			response.setErrorcode(1);
			response.setMessage("添加请假信息失败...");
		}
		return response;
	}

	@Override
	public RestResponse getLeaveType(RestResponse response)
			throws DataAccessException {
		List<Map<String,Object>> leaveType = teacherDao.getLeaveType();
		if (leaveType!= null && leaveType.size() > 0) {
			response.setErrorcode(0);
			response.setData(leaveType);
		} else {
			response.setErrorcode(1);
			response.setMessage("系统未获取到数据...");
		}
		return response;
	}
	
	

}
